//不自动审核
import CommonInput from "@/pages/OrderModule/common/components/CommonInput";
import CommonInputNumber from "@/pages/OrderModule/common/components/CommonInputNumber";
import { CommonModal } from "@/views/components/CommonModal";
import CommonText from "@/pages/OrderModule/common/components/CommonText/CommonText";
import SubTitle from "@/pages/OrderModule/common/components/SubTitle";
import { useAnchor } from "@/pages/OrderModule/common/hooks/useAnchor";
import FiledWrapper from "@/pages/OrderModule/orderList/components/Filter/components/FieldWrapper";
import { Button, Form, Radio, Select, Tabs, Checkbox, Space, message } from "antd";
import { useEffect, useRef, useState } from "react";
import FormRowWrapper from "../FormRowWrapper";
import { saveNotAutoReviewStrategyOp, notAutoReviewStrategyOp, updateNotAutoReviewStrategyOp } from "../../service";
import Style from "./index.module.less";
import { isEmpty, isNil, find } from "lodash";
import CommonLoading from "@/components/CommonLoading";
import BatchSuffixInput from "@/views/components/BatchSuffixInput";
import SelectTag from "@/components/SelectTag";
import IconFont from "@/components/IconFont";
import SelectShop from "@/components/SelectShop";
import { labelTypeMap, labelColorMap } from "@/utils/config";
import { getAllowClearProps } from "../../helpers/constant";

//弹窗标题
const titleMap = {
	add: "新增",
	edit: "编辑",
	view: "查看"
};

//旗帜🚩
//旗帜
const checkboxList = [
	{
		label: <CommonText extractIcon={<IconFont type="iconqizhihong"></IconFont>} />,
		value: 1
	},
	{
		label: <CommonText extractIcon={<IconFont type="iconqizhihuang"></IconFont>} />,
		value: 2
	},
	{
		label: <CommonText extractIcon={<IconFont type="iconqizhilv"></IconFont>} />,
		value: 3
	},
	{
		label: <CommonText extractIcon={<IconFont type="iconqizhilan"></IconFont>} />,
		value: 4
	},

	{
		label: <CommonText extractIcon={<IconFont type="iconqizhizi"></IconFont>} />,
		value: 5
	}
];

const formCategoryList = [
	{
		key: "intelligent-form__ruleName",
		title: "规则名称",
		render(node) {
			return (
				<div id={this.key}>
					<SubTitle title={this.title} as="s2" symbol />
					{node}
				</div>
			);
		}
	},
	{
		key: "intelligent-form__notAutoReview",
		title: "不自动审核条件",
		render(node) {
			return (
				<div id={this.key}>
					<SubTitle title={this.title} as="s2" symbol />
					{node}
				</div>
			);
		}
	}
];

const AddNotAutoReviewRule = ({ visible, type, recordData, handleCancel, handleOk }) => {
	const [detailData, setDetailData] = useState({}); //详情数据
	const [tab, setTab] = useState(formCategoryList[0].key);
	const formWrapperRef = useRef(null);
	const anchorItems = useRef({});
	const { currentAnchor, scrollToAnchor } = useAnchor(formWrapperRef, anchorItems);
	const [labelVisible, setLabelVisible] = useState(false); //是否展示标签弹窗
	const [selectLabels, setSelectLabels] = useState([]); //选择订单标签
	const [shopVisible, setShopVisible] = useState(false); //店铺组件弹窗
	const [selectShops, setSelectShops] = useState([]); //选择的店铺
	const [loading, setLoading] = useState(false);

	const [form] = Form.useForm();

	const labelRule = Form.useWatch("labelRule", form);
	const buyerMessageRule = Form.useWatch("buyerMessageRule", form);
	const sellerMessageRule = Form.useWatch("sellerMessageRule", form);
	const flagRule = Form.useWatch("flagRule", form);

	useEffect(() => {
		formCategoryList.forEach(item => {
			anchorItems.current[item.key] = document.getElementById(item.key) != null ? document.getElementById(item.key) : undefined;
		});
	}, []);

	useEffect(() => {
		if (currentAnchor) {
			setTab(currentAnchor);
		}
	}, [currentAnchor]);

	useEffect(() => {
		if (visible) {
			form.resetFields();
			if (!isEmpty(recordData)) {
				getNotAutoReviewStrategyOp();
			}
		}
	}, [visible, recordData]);

	useEffect(() => {
		if (!isEmpty(detailData)) {
			form.resetFields();
			if (detailData.labelConfigList) {
				setSelectLabels(detailData.labelConfigList);
			}
			if (detailData.ecStoreList) {
				setSelectShops(detailData.ecStoreList);
			}
		}
	}, [detailData]);

	useEffect(() => {
		if (selectLabels.length) {
			form.setFieldsValue({
				labelIds: selectLabels.map(item => (labelTypeMap[item.name] ? labelColorMap[item.name] : item.name)).join(",")
			});
		} else {
			form.setFieldsValue({ labelIds: "" });
		}
	}, [selectLabels]);

	useEffect(() => {
		if (selectShops.length) {
			form.setFieldsValue({
				ecStoreIds: selectShops.map(item => (item.systemStoreName ? item.systemStoreName : item.storeName)).join(",")
			});
		} else {
			form.setFieldsValue({ ecStoreIds: "" });
		}
	}, [selectShops]);

	//新增/编辑智能标签规则
	const saveNotAutoReviewStrategy = async val => {
		setLoading(true);
		let res;
		const params = {
			...val,
			labelIds: selectLabels.length > 0 ? selectLabels.map(item => item.id).join(",") : undefined,
			flags: !isNil(val.flags) ? val.flags.join(",") : undefined,
			ecStoreIds: selectShops.length > 0 ? selectShops.map(item => item.id).join(",") : undefined
		};
		if (type == "add") {
			res = await saveNotAutoReviewStrategyOp(params);
		} else {
			params.id = recordData.id;
			res = await updateNotAutoReviewStrategyOp(params);
		}
		const { success, msg = "" } = res;
		if (success) {
			message.success(msg);
			handleOk();
		}
		setLoading(false);
	};

	//智能标签规则详情
	const getNotAutoReviewStrategyOp = async () => {
		setLoading(true);
		const { success, data = {} } = await notAutoReviewStrategyOp({
			id: recordData.id
		});
		if (success) {
			setDetailData(data);
		}
		setLoading(false);
	};

	const onFinish = values => {
		form
			.validateFields()
			.then(val => {
				saveNotAutoReviewStrategy(val);
			})
			.catch(err => {});
	};

	const onFinishFailed = errorInfo => {
		console.log("Failed:", errorInfo);
	};

	const renderNumberArea = () => {
		const renderInputNumber = (label, field1, field2) => {
			const numberInputProps = { controls: false, min: 0, placeholder: "请输入", disabled: type == "view" };
			const minValue = form.getFieldValue(field1),
				maxValue = form.getFieldValue(field2);
			return (
				<>
					<FiledWrapper
						label={label}
						labelHigh={minValue || maxValue ? true : false}
						childrenStyle={{ display: "flex" }}
						style={{ marginTop: 16, paddingLeft: 12 }}
					>
						<Form.Item name={field1} noStyle>
							<CommonInputNumber {...numberInputProps} />
						</Form.Item>
						<i className="connector" />
						<Form.Item name={field2} noStyle>
							<CommonInputNumber {...numberInputProps} />
						</Form.Item>
					</FiledWrapper>
				</>
			);
		};

		return (
			<>
				<div style={{ marginBottom: -16 }}></div>
				{FormRowWrapper([
					renderInputNumber("订单金额", "minOrderAmount", "maxOrderAmount"),
					renderInputNumber("商品数量", "minGoodsNum", "maxGoodsNum"),
					renderInputNumber("订单重量", "minOrderWeight", "maxOrderWeight")
				])}
				<div style={{ marginBottom: 16 }}></div>
			</>
		);
	};

	//清除店铺/标签弹窗
	const handleClear = (e, code) => {
		const val = e.target.value;
		if (val == "") {
			if (code == "store") {
				setSelectShops([]);
			} else {
				setSelectLabels([]);
			}
		}
	};

	//标签弹窗
	const SelectTagProps = {
		selectLabels: selectLabels.map(item => item.id),
		showFilterMethod: false,
		handleCancel() {
			setLabelVisible(false);
		},
		handleDealData(selectTag, realData) {
			const arr = [];
			selectTag.forEach(item => {
				const obj = find(realData, ["id", item]);
				arr.push(obj);
			});
			return arr;
		},
		handleOK(val) {
			setLabelVisible(false);
			if (val.length) {
				setSelectLabels(val);
			}
		}
	};

	//店铺组件
	const SelectShopProps = {
		selectShops: selectShops.map(item => item.id),
		handleCancel() {
			setShopVisible(false);
		},
		handleOk(arr) {
			setShopVisible(false);
			setSelectShops(arr);
		}
	};

	return (
		<>
			<CommonModal
				title={{ title: `${titleMap[type]}不自动审核规则` }}
				open={visible}
				onCancel={handleCancel}
				width={834}
				destroyOnClose
				// onOk={onFinish}
				footer={[
					<Button key="back" onClick={handleCancel}>
						取消
					</Button>,
					<Button disabled={type == "view"} key="save" htmlType="submit" onClick={onFinish} type="primary">
						保存
					</Button>
				]}
			>
				<div className={Style["modal-content"]}>
					<Tabs
						activeKey={tab}
						onChange={val => {
							scrollToAnchor(val);
						}}
					>
						{formCategoryList.map(item => (
							<Tabs.TabPane tab={item.title} key={item.key}></Tabs.TabPane>
						))}
					</Tabs>
					<div ref={formWrapperRef} className={Style["modal-form"]}>
						<Form
							name="basic"
							onFinish={onFinish}
							onFinishFailed={onFinishFailed}
							form={form}
							autoComplete="off"
							layout="horizontal"
							labelAlign="right"
							initialValues={{
								...detailData,
								flags: detailData.flags ? detailData.flags.split(",") : undefined,
								buyerMessageRule: detailData.buyerMessageRule || 1,
								sellerMessageRule: detailData.sellerMessageRule || 1,
								flagRule: detailData.flagRule || 1,
								goodsRule: detailData.goodsRule || 1,
								labelRule: detailData.labelRule || 1,
								outUniqueCodeRule: detailData.outUniqueCodeRule || 1
							}}
						>
							{formCategoryList[0].render()}
							{FormRowWrapper([
								<Form.Item rules={[{ required: "true", message: "请输入标签规则名称" }]} name="name">
									<CommonInput
										disabled={type == "view"}
										placeholder="请输入不自动审核规则名称"
										maxLength={30}
										showCount
										aria-required
										allowClear
									/>
								</Form.Item>,
								<Form.Item
									rules={[
										{ required: "true", message: "请输入优先级" },
										{
											pattern: /^[1-9]\d*$/g,
											message: "请输入正整数"
										}
									]}
									name="level"
								>
									<CommonInputNumber disabled={type == "view"} placeholder="必填，优先级" aria-required min={1} max={100} allowClearProps={getAllowClearProps(form)} />
								</Form.Item>
							])}
							{formCategoryList[1].render()}
							{FormRowWrapper([
								<Form.Item name="ecStoreIds">
									<CommonInput
										// {...inputProps}
										// readOnly
										allowClear
										onClick={() => setShopVisible(true)}
										onChange={e => handleClear(e, "store")}
										placeholder="请选择店铺"
										disabled={type == "view"}
										style={{ width: "200px" }}
										suffix={
											<IconFont onClick={() => setShopVisible(true)} style={{ cursor: "pointer" }} type="iconmodal-input" />
										}
									/>
								</Form.Item>
							])}
							<Form.Item name="buyerMessageRule" label="买家留言">
								<Radio.Group disabled={type == "view"}>
									<Radio value={1}>不判断</Radio>
									<Radio value={2}>有留言</Radio>
									<Radio value={3}>包含以下留言</Radio>
								</Radio.Group>
							</Form.Item>
							{buyerMessageRule == 3 ? (
								<Form.Item name="buyerMessage" wrapperCol={{ offset: 2 }}>
									<BatchSuffixInput
										clearable
										allowClear
										autoMultiLine
										modalProps={{
											title: "批量输入"
										}}
										maxItem={500}
										placeholder="请输入留言备注关键字，多个逗号隔开"
										message="分行输入内容，提交后主页面输入框会按照逗号自动隔开，点击查询可批量查询。"
										areaPlaceholder="每行输入1个内容，最多500个，例如:&#10;1272572508553111112223&#10;1272572512332111112226"
										disabled={type == "view"}
									/>
								</Form.Item>
							) : (
								""
							)}
							<Form.Item name="sellerMessageRule" label="卖家备注">
								<Radio.Group disabled={type == "view"}>
									<Radio value={1}>不判断</Radio>
									<Radio value={2}>有备注</Radio>
									<Radio value={3}>包含以下备注</Radio>
								</Radio.Group>
							</Form.Item>
							{sellerMessageRule == 3 ? (
								<Form.Item name="sellerMessage" wrapperCol={{ offset: 2 }}>
									<BatchSuffixInput
										clearable
										allowClear
										autoMultiLine
										modalProps={{
											title: "批量输入"
										}}
										maxItem={500}
										placeholder="请输入留言备注关键字，多个逗号隔开"
										message="分行输入内容，提交后主页面输入框会按照逗号自动隔开，点击查询可批量查询。"
										areaPlaceholder="每行输入1个内容，最多500个，例如:&#10;1272572508553111112223&#10;1272572512332111112226"
										disabled={type == "view"}
									/>
								</Form.Item>
							) : (
								""
							)}
							<Form.Item name="flagRule" label="旗帜" style={{ marginLeft: "28px" }}>
								<Radio.Group disabled={type == "view"}>
									<Radio value={1}>不判断</Radio>
									<Radio value={2}>有旗帜</Radio>
									<Radio value={3}>包含以下旗帜</Radio>
								</Radio.Group>
							</Form.Item>
							{flagRule == 3 ? (
								<Form.Item name="flags" wrapperCol={{ offset: 2 }}>
									<Checkbox.Group disabled={type == "view"} style={{ width: "100%" }}>
										<Space direction="horizontal">
											{checkboxList.map(item => (
												<Checkbox key={item.value} value={item.value + ""}>
													{item.label}
												</Checkbox>
											))}
										</Space>
									</Checkbox.Group>
								</Form.Item>
							) : (
								""
							)}
							<Form.Item name="goodsRule" label="商品匹配" colon>
								<Radio.Group disabled={type == "view"}>
									<Radio value={1}>不判断</Radio>
									<Radio value={2}>有商品未匹配</Radio>
								</Radio.Group>
							</Form.Item>
							<Form.Item name="labelRule" label="订单标签" colon>
								<Radio.Group disabled={type == "view"}>
									<Radio value={1}>不判断</Radio>
									<Radio value={2}>有标签</Radio>
									<Radio value={3}>包含以下标签</Radio>
								</Radio.Group>
							</Form.Item>
							{labelRule == 3 ? (
								<Form.Item name="labelIds" wrapperCol={{ offset: 2 }}>
									<CommonInput
										// readOnly
										allowClear
										disabled={type == "view"}
										onClick={() => setLabelVisible(true)}
										onChange={e => handleClear(e, "orderTag")}
										placeholder="请选择订单标签"
										suffix={
											<IconFont onClick={() => setLabelVisible(true)} style={{ cursor: "pointer" }} type="iconmodal-input" />
										}
									/>
								</Form.Item>
							) : (
								""
							)}
							{renderNumberArea()}
							<Form.Item name="outUniqueCodeRule" label="是否有外部唯一码">
								<Radio.Group disabled={type == "view"}>
									<Radio value={1}>不判断</Radio>
									<Radio value={2}>有外部唯一码</Radio>
									<Radio value={3}>无外部唯一码</Radio>
								</Radio.Group>
							</Form.Item>
						</Form>
					</div>
				</div>
				{labelVisible && <SelectTag {...SelectTagProps} />}
				{shopVisible && <SelectShop {...SelectShopProps} />}
				<CommonLoading loading={loading} />
			</CommonModal>
		</>
	);
};

export default AddNotAutoReviewRule;
